package leetcode_acm.backtrack;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 功能描述
 *
 * @author: 张庭杰
 * @date: 2023年03月22日 22:26
 */
public class CombinationSum2 {
    private List<List<Integer>> list;
    private boolean[] used;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        list = new LinkedList<>();
        Arrays.sort(candidates);
        used = new boolean[candidates.length];
        backtrack(candidates,0,target,new LinkedList<>());
        return list;
    }
    private void backtrack(int[] nums,int startIndex,int sum,LinkedList<Integer> path){
        if(sum == 0){
            list.add(new LinkedList<>(path));
            return ;
        }
        for(int i = startIndex; i < nums.length;i++){
            //如果存在树层的重复,直接跳过
            if(i > 0 && nums[i-1] == nums[i] && !used[i - 1]){
                continue;
            }
            if(sum - nums[i] < 0){
                return ;
            }
            path.addLast(nums[i]);
            used[i] = true;
            backtrack(nums,i+1,sum - nums[i],path);
            path.removeLast();
            used[i] = false;
        }
    }
}
